<template>
  <div style="display: flex;">
    <!-- 左侧菜单栏 -->
    <div :style="{width:( isCollapse ? '64px': '208px')}">
      <el-menu
          background-color="#c4e2fb"
          style="width:100%;height:100vh;"
          text-color="#555555"
          active-text-color="#ff0"
          :collapse="isCollapse"
          :collapse-transition="false"
          unique-opened router
      >
        <!-- 顶部logo和标题 -->
        <el-row style="padding-top: 10px;">
          <el-col :span="2"></el-col>
          <el-col :span="7" style="padding-left:7px;">
            <el-avatar src="/imgs/admin/logo.png" style="width:35px;height:35px;"></el-avatar>
          </el-col>
          <el-col :span="isCollapse ? 0 : 13">
            <span style="color:#555555;position:relative;top:8px;left:2px;font-weight: bold;">
              安心陪诊
            </span>
          </el-col>
        </el-row>

        <!-- 个人中心菜单 -->
        <el-sub-menu index="1">
          <template #title>
            <el-icon style="font-size:21px;"><User/></el-icon><span>个人中心</span>
          </template>
          <el-menu-item index="/user/first">首页</el-menu-item>
          <el-menu-item index="/user/profile">个人信息</el-menu-item>
        </el-sub-menu>

        <!-- 我的预约菜单 -->
        <el-sub-menu index="2">
          <template #title>
            <el-icon style="font-size:21px;"><Calendar/></el-icon>
            <span>我的预约</span>
          </template>
          <el-menu-item index="/user/appointments">预约列表</el-menu-item>
        </el-sub-menu>

        <!-- 我的收藏菜单 -->
        <el-sub-menu index="3">
          <template #title>
            <el-icon style="font-size:21px;"><Star/></el-icon>
            <span>我的收藏</span>
          </template>
          <el-menu-item index="/user/favorites">收藏列表</el-menu-item>
        </el-sub-menu>

        <!-- 我的评价菜单 -->
        <el-sub-menu index="4">
          <template #title>
            <el-icon style="font-size:21px;"><ChatLineRound/></el-icon>
            <span>我的评价</span>
          </template>
          <el-menu-item index="/user/reviews">评价列表</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>

    <!-- 右侧内容区 -->
    <div :style="{width:( isCollapse ? 'calc(100% - 64px)': 'calc(100% - 208px)')}">
      <!-- 顶部导航栏 -->
      <el-header style="padding-top:22px;height:10vh;background-color:#fff;">
        <el-row :gutter="10">
          <el-col :span="18">
            <el-icon style="font-size:20px;" @click="changeCollapsed"><Expand/></el-icon>
          </el-col>
          <el-col :span="6" style="position: relative;">
            <el-dropdown trigger="click" style="position:absolute;right:20px;">
              <span style="font-size:19px;font-weight: bold;">
                {{ userInfo.username }}
                <el-icon><arrow-down/></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>

        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" style="position: relative;top: 20px;">
          <el-breadcrumb-item v-for="item in breadcrumb">{{item}}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>

      <!-- 主内容区 -->
      <el-main style="height:90vh;padding: 0;overflow-y: auto;">
        <router-view/>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import {onMounted, ref} from "vue";
import { useRoute, useRouter } from "vue-router";
import {ElMessage} from "element-plus";

const loading = ref(true);
const userData = ref(null); // 改为明确的null初始化

// 菜单折叠状态
const isCollapse = ref(false);
// 切换折叠状态
const changeCollapsed = () => {
  isCollapse.value = !isCollapse.value;
}

// 用户信息
const userInfo = ref({
  id: "",
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: "",
  createTime: ""
});

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;

    // 优先检查本地存储
    const localUser = localStorage.getItem('user');
    if (localUser) {
      userData.value = JSON.parse(localUser);
    }

    console.log(userData);

    // 强制从接口获取最新数据
    const response = await axios.get(`${BASE_URL}/v1/user/info`, {
      withCredentials: true
    });

    if (response.data?.data) {
      // 同步更新两个状态
      userInfo.value = response.data.data;
      userData.value = response.data.data;
      localStorage.setItem('user', JSON.stringify(response.data.data));
    } else {
      throw new Error('无效的用户数据');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);

    // 根据错误状态处理
    if (error.response?.status === 401) {
      ElMessage.warning('请重新登录');
      localStorage.removeItem('user');
      router.push('/login');
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } finally {
    loading.value = false;
  }
};

// 退出登录
const logout = async () => {
  if(confirm('您确认要退出登录吗?')){
    try {
      // 调用后端退出接口
      await axios.post(BASE_URL+'/v1/user/logout');
    } catch (error) {
      console.error("退出登录出错:", error);
    } finally {
      // 清除前端存储
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
    }
  }
}

// 面包屑导航
const breadcrumb = ref([]);
let map = {
  '/user/first': ['个人中心', '首页'],
  '/user/profile': ['个人中心', '个人信息'],
  '/user/appointments': ['我的预约', '预约列表'],
  '/user/favorites': ['我的收藏', '收藏列表'],
  '/user/reviews': ['我的评价', '评价列表']
};

onMounted(() => {
  // 立即从本地存储初始化
  const localUser = localStorage.getItem('user');
  if (localUser) {
    userInfo.value = JSON.parse(localUser);
  }

  fetchUserInfo();
  updateBreadcrumb(route);
})

const route = useRoute();
// 更新面包屑
const updateBreadcrumb = (route) => {
  const path = route.path;
  breadcrumb.value = map[path];
}

const router = useRouter();
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})
</script>